import { BaseAgentBackend, AgentBackendFactory } from "../../../public/agentBackend";
import { getEnv, EnvEnum } from "../../../public/env";
import { eclConfig } from "../config";

export interface EmbeddingConfig {
    modelMaker: string;
    embeddingModelType: string;
    promptTokenCount?: number;
    propmtTotalCount?: number;
}

export class EmbeddingBackend {
    public modelMaker: string;
    public embeddingModelType: string;

    private key: string;
    private modelBackend: typeof BaseAgentBackend;

    constructor(embeddingConfig?: EmbeddingConfig) {
        const config = { ...eclConfig.defaultEmbeddingConfig, ...embeddingConfig };

        this.modelMaker = config.modelMaker;
        this.embeddingModelType = config.embeddingModelType;

        this.key = getEnv(EnvEnum.AGENT_BACKEND_API_KEY);
        this.modelBackend = AgentBackendFactory.create(this.modelMaker);
    }

    async getEmbedding(content: string): Promise<number[]> {
        const validatedContent = this.validateContent(content);
        const response = await this.modelBackend.getTextEmbedding({
            apiKey: this.key,
            input: validatedContent,
            model: this.embeddingModelType
        });
        const embedding = response.data[0].embedding;
        return embedding;
    }

    private validateContent(content: string): string {
        if (content.length > 8191) {
            return content.substring(0, 8190);
        }
        return content;
    }
}
